package cn.xclink.kernel.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.xclink.common.mapper.BaseMapper;
import cn.xclink.common.service.BaseService;
import cn.xclink.kernel.cache.CacheDic;
import cn.xclink.kernel.entity.Dic;
import cn.xclink.kernel.entity.DicItem;
import cn.xclink.kernel.mapper.DicItemMapper;
import cn.xclink.kernel.mapper.DicMapper;

@Service("dicService")
public class DicService extends BaseService<Dic> {

	@Autowired
	private DicMapper mapper;

	@Autowired
	private DicItemMapper dicItemMapper;

	@Override
	public BaseMapper<Dic> getMapper() {
		return mapper;
	}

	@Override
	public List<Dic> find(Dic record) {
		return mapper.selectExt(record);
	}

	@Override
	public int delete(Object dicTypeCode) {
		dicItemMapper.delete(new DicItem(Long.parseLong(dicTypeCode+"")));
		return mapper.deleteByPrimaryKey(dicTypeCode);
	}

	/**
	 * 初始化数据字典缓存
	 */
	public void initCache() {
		List<Dic> dicList = mapper.selectAll();
		CacheDic.dicMap.clear();
		CacheDic.dicItemMap.clear();
		CacheDic.dicItemList.clear();
		for (Dic dic : dicList) {
			CacheDic.dicMap.put(dic.getDicTypeCode(),dic);
			List<DicItem> dictItemList = dicItemMapper.select(new DicItem(dic.getDicId()));
			CacheDic.dicItemList.put(dic.getDicTypeCode(), dictItemList);
			Map<String, String> map = new HashMap<String, String>();
			for (DicItem dicItem : dictItemList) {
				map.put(dicItem.getDicItemTypeCode(),dicItem.getDicItemName());  
			}
			CacheDic.dicItemMap.put(dic.getDicTypeCode(),map);  
		}
	}
}
